import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class BudgetManagementDialog extends JDialog {
    private JTextField yearField;
    private JTextField monthField;
    private JTextField budgetField;
    private Map<String, Integer> budgets;

    public BudgetManagementDialog(JFrame owner) {
        super(owner, "预算管理", true);
        setSize(400, 200);
        setLocationRelativeTo(owner); // 居中显示
        setLayout(new GridLayout(5, 1, 9, 9));

        // 创建输入字段
        yearField = new JTextField();
        monthField = new JTextField();
        budgetField = new JTextField();

        // 加载已有预算
        budgets = loadBudgets();

        // 添加标签和输入字段
        add(new JLabel("年份 (yyyy):"));
        add(yearField);
        add(new JLabel("月份 (MM):"));
        add(monthField);
        add(new JLabel("预算金额:"));
        add(budgetField);

        // 创建保存按钮
        JButton saveButton = new JButton("保存");
        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String yearStr = yearField.getText().trim();
                String monthStr = monthField.getText().trim();
                String budgetStr = budgetField.getText().trim();

                // 收集所有错误信息
                StringBuilder errorMessages = new StringBuilder();

                if (!validateYearMonth(yearStr, monthStr)) {
                    errorMessages.append("请输入有效的年份和月份格式 (yyyy, MM)。\n");
                }

                if (!validateBudget(budgetStr)) {
                    errorMessages.append("预算金额必须为正整数。\n");
                }

                // 如果有错误信息，则显示并返回
                if (errorMessages.length() > 0) {
                    JOptionPane.showMessageDialog(BudgetManagementDialog.this, errorMessages.toString(), "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                // 保存预算
                saveBudget(yearStr, monthStr, budgetStr);
                JOptionPane.showMessageDialog(BudgetManagementDialog.this, "预算已保存。");
                dispose(); // 关闭对话框
            }
        });

        // 添加保存按钮
        add(saveButton);
    }

    private boolean validateYearMonth(String yearStr, String monthStr) {
        try {
            int year = Integer.parseInt(yearStr);
            int month = Integer.parseInt(monthStr);
            if (year < 0 || month < 1 || month > 12) {
                return false;
            }
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    private boolean validateBudget(String budgetStr) {
        try {
            int budget = Integer.parseInt(budgetStr);
            return budget > 0;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    private void saveBudget(String year, String month, String budgetStr) {
        String key = year + "-" + month;
        int budget = Integer.parseInt(budgetStr);
        budgets.put(key, budget);

        String filePath = "Gitzuoye/src/budgets";
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
            for (Map.Entry<String, Integer> entry : budgets.entrySet()) {
                writer.write(entry.getKey() + "," + entry.getValue());
                writer.newLine();
            }
        } catch (IOException e) {
            JOptionPane.showMessageDialog(this, "无法保存预算，请检查文件路径或权限。", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private Map<String, Integer> loadBudgets() {
        Map<String, Integer> budgets = new HashMap<>();
        String filePath = "Gitzuoye/src/budgets";
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split(",");
                if (parts.length == 2) {
                    budgets.put(parts[0], Integer.parseInt(parts[1]));
                }
            }
        } catch (IOException e) {
            // 文件不存在或读取失败，忽略
        }
        return budgets;
    }
}